﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GMap.NET.WindowsPresentation;

namespace ImmovablesManager
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Login _loginWindow;
        private DateTime? _timeEnterUser;
        public MainWindow()
        {
            _loginWindow = new Login();
            _loginWindow.ShowDialog();
            if (!_loginWindow.IsCorrect)
                Close();

          
            InitializeComponent();
            UserName.Content = Login.UserName;

            if(Login.Role == "controller")
            {
                BtnStoryLog.Visibility = Visibility.Visible;
                BtnRealtorManagement.Visibility = Visibility.Visible;
                _timeEnterUser = DateTime.Now;
            }
            else
            {
                if (Login.Role == "director")
                {
                    _timeEnterUser = DateTime.Now;
                }
                else
                {
                    if (Login.Role == "user")
                    {
                        BtnUserEntranceLog.Visibility = Visibility.Visible;
                    }
                }

            }

            FormNewFlatDataGridView();
        }

        public void FormPlotDataGridView()
        {
           
        }



        public void FormFlatDataGridView()
        {
            var flats = AppController.ImmoRepository.GetAllFlats();
            AddFlatDataGridView(flats);
            
        }

        private void AddFlatDataGridView(IEnumerable<Flat> flats)
        {
            var dataGridFlatsDataViews = new ObservableCollection<DataGridFlatsDataView>();
            foreach (var flat in flats)
            {
                dataGridFlatsDataViews.Add(new DataGridFlatsDataView
                {
                    FlatId = flat.FlatId,
                    Floor = flat.FlatFloor,
                    FloorsCount = flat.FlatFloors,
                    Material = flat.HouseMaterial.HouseMaterialName,
                    RoomCount = flat.FlatRoomCount,
                    TotalArea = flat.FlatTotalArea,
                    AdditionalDescription = flat.FlatAdditionalInformation,
                    IRR = flat.FlatIRR,
                    KitchenArea = flat.FlatKitchenArea,
                    LivingArea = flat.FlatLivingArea,
                    TotalCost = flat.FlatTotalCost,
                    Note = flat.FlatNote,
                    Address = flat.FlatAddress
                });
            }
            DataGridFlats.ItemsSource = dataGridFlatsDataViews;
        }

        

        public void FormNewFlatDataGridView()
        {
            var newFlats = AppController.ImmoRepository.GetAllNewFlats();
            AddNewFlatDataGridView(newFlats);

        }

        private void AddNewFlatDataGridView(IEnumerable<NewFlat> newFlats)
        {
            var dataGridNewFlatsDataViews = new ObservableCollection<DataGridNewFlatsDataView>();

            foreach (var flat in newFlats)
            {
                dataGridNewFlatsDataViews.Add(new DataGridNewFlatsDataView()
                {
                    NewFlatId = flat.NewFlatId,
                    NewFloor = flat.NewFlatFloor,
                    NewFloorsCount = flat.NewFlatFloorsCount,
                    NewMaterial = flat.HouseMaterial.HouseMaterialName,
                    NewRoomCount = flat.NewFlatRoomsCount,
                    NewTotalArea = flat.NewFlatTotalArea,
                    NewAdditionalDescription = flat.NewFlatAdditionalInfo,
                    NewIRR = flat.NewFlatIRR,
                    NewKitchenArea = flat.NewFlatKitchenArea,
                    NewLivingArea = flat.NewFlatLivingArea,
                    NewTotalCost = flat.NewFlatTotalCost,
                    NewNote = flat.NewFlatNote,
                    NewAddress = flat.NewFlatAddress,
                    NewCostPerMeter = flat.NewFlatCostPerMeter,
                    NewBuildingFinishedDate = flat.NewFlatBuildingFinishedDate
                });
            }

            DataGridNewFlats.ItemsSource = dataGridNewFlatsDataViews;
        }

        public void FormCommercialDataGridView()
        {
            var commercials = AppController.ImmoRepository.GetAllCommercial();
            AddCommercialGridView(commercials);
        }

        private void AddCommercialGridView(IEnumerable<CommercialRealEstate> commercials)
        {
               var dataGridCommercialDataView = new ObservableCollection<DataGridCommercialDataView>();

            foreach (var commercial in commercials)
            {
                dataGridCommercialDataView.Add(new DataGridCommercialDataView()
                                                   {
                                                       CommercialId = commercial.CommercialRealEstatetId,
                                                       CommercialAddress = commercial.CommercialRealEstateAddress,
                                                       CommercialContractNumber = commercial.CommercialRealEstateContractNumber,
                                                       CommercialFloor = commercial.CommercialRealEstateFloor,
                                                       CommercialFloorsCount = commercial.CommercialRealEstateMaxFloors,
                                                       CommercialRegion = commercial.Region.RegionName,
                                                       CommercialWallsMaterial = commercial.CommercialRealEstateWallsMaterial.CommercialRealEstateWallsMaterialName,
                                                       CardNumber = commercial.FinancialData.FinancialDataCardNumber,
                                                       GeneralInformation = commercial.CommercialRealEstateGeneralInformation,
                                                       OwnerPhone = commercial.Owner.OwnerMobilePhone,
                                                       TotalArea = commercial.CommercialRealEstateTotalArea,
                                                       TotalCost = commercial.CommercialRealEstateTotalCost,
                                                       CommercialType = commercial.CommercialRealEstateType.CommercialRealEstateTypeName,
                                                       RealtorPhone = commercial.FinancialData.User.UserPhoneNumber,
                                                   });
            }

            DataGridCommercial.ItemsSource = dataGridCommercialDataView;
        }

        public void FormPlotsDataGridView()
        {
            var plots = AppController.ImmoRepository.GetAllPlots();
            AddPlotGridView(plots);
        }
        
        private void AddPlotGridView(IEnumerable<Plots> plots)
        {
             var dataGridPlotsDataViews = new ObservableCollection<DataGridPlotsDataView>();
            foreach (var plot in plots)
            {
                dataGridPlotsDataViews.Add(new DataGridPlotsDataView()
                {
                    PlotId = plot.PlotsId,
                    PlotAddress = plot.PlotsAddress,
                    PlotContractNumber = plot.FinancialData.FnancialDataContract,
                    PlotRegion = plot.Region.RegionName,
                    OwnerPhone = plot.Owner.OwnerHomePhone,
                    TotalArea = plot.PlotsArea,
                    TotalCost = plot.FinancialData.FinancialDataPrice,
                    CardNumber = plot.FinancialData.FinancialDataCardNumber,
                    RealtorPhone = plot.FinancialData.User.UserPhoneNumber,
                    GeneralInformation = plot.PlotsAdditionalInformation
                });
            }

            DataGridPlots.ItemsSource = dataGridPlotsDataViews;
        }

        private void MainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(e.Source is TabControl)) return;
            var tabControl = (TabControl)e.Source;
            switch (tabControl.SelectedIndex)
            {
                case (0):
                    {
                        FormFlatDataGridView();
                        break;
                    }
                case (1):
                    {
                        FormNewFlatDataGridView();
                        break;
                    }
                case (2):
                    {
                        FormCommercialDataGridView();
                        break;
                    }
                case (3):
                    {
                        FormPlotsDataGridView();
                        break;
                    }
            }
        }

        private void BtnRealtorManagement_Click(object sender, RoutedEventArgs e)
        {
            Realtors realtor = new Realtors();
            realtor.ShowDialog();
        }

        private void BtnStoryLog_Click(object sender, RoutedEventArgs e)
        {
            Log log = new Log();
            log.ShowDialog();
        }

        private void MenuItemVersion_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Версия программы","Milestone 1.0");
        }

        private void BtnShowFlat_Click(object sender, RoutedEventArgs e)
        {

        }

        private void DataGridFlats_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

       
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            var newFlatCard = new NewFlatCard(new Guid(),false);
            newFlatCard.ShowDialog();
        }

        private void MenuItem_Click_1(object sender, RoutedEventArgs e)
        {
            var commercialCard = new CommercialCard();
            commercialCard.ShowDialog();
        }

        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            var flatCard = new FlatCard(new Guid(), false);
            flatCard.ShowDialog();
        }

        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            var plotCard = new PlotCard();
            plotCard.ShowDialog();
        }

        private void DataGridFlats_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (DataGridFlats.SelectedItem == null) return;
            var selectedFlat = DataGridFlats.SelectedItem as DataGridFlatsDataView;

            if (selectedFlat != null)
            {
                var newFlatCard = new FlatCard(selectedFlat.FlatId, true);
                newFlatCard.ShowDialog();
            }
        }

        private void DataGridNewFlats_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (DataGridNewFlats.SelectedItem == null) return;
            var selectedNewFlat = DataGridNewFlats.SelectedItem as DataGridNewFlatsDataView;

            var newFlatCard = new NewFlatCard(selectedNewFlat.NewFlatId, true);
            newFlatCard.ShowDialog();
        }

        private void DataGridCommercial_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (DataGridCommercial.SelectedItem == null) return;
            var selectedCommercial = DataGridCommercial.SelectedItem as DataGridCommercialDataView;

            if (selectedCommercial != null)
            {
                var newCard = new CommercialCard(selectedCommercial.CommercialId);
                newCard.ShowDialog();
            }
        }

        private void DataGridPlots_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (DataGridPlots.SelectedItem == null) return;
            var selectedPlot = DataGridPlots.SelectedItem as DataGridPlotsDataView;

            if (selectedPlot != null)
            {
                var newFlatCard = new PlotCard(selectedPlot.PlotId);
                newFlatCard.ShowDialog();
            }
        }


        private void BtnUserEntranceLog_Click(object sender, RoutedEventArgs e)
        {
            var userEntranceLog = new UserEntranceLog();
            userEntranceLog.ShowDialog();
        }

        private void Closed_MainWindow(object sender, EventArgs e)
        {
            if (Login.Role == "controller" || Login.Role == "director")
            {
                AppController.ImmoRepository.AddUserEntrance(Login.UserId, _timeEnterUser, DateTime.Now);
            }
        }

        #region Filter

        private void BtnFilter_Click(object sender, RoutedEventArgs e)
        {
            //if (!(e.Source is TabControl)) return;
            //var tabControl = (TabControl)e.Source;
            switch (MainTabControl.SelectedIndex)
            {
                case (0):
                    {
                        filterNewFlat();
                        break;
                    }
                case (1):
                    {
                        filterFlat();
                        break;
                    }
                case (2):
                    {
                        filterCommercial();
                        break;
                    }
                case (3):
                    {
                        filterPlot();
                        break;
                    }
            }
           
        }

        private void filterFlat()
        {
            var filter = new FilterWindow(TypeObject.Flat);
            filter.ShowDialog();
            #region filterFlat
            if (filter.filterFlat != null)
            {
                var flats = AppController.ImmoRepository.GetAllFlats();
                var filteredList = flats;

                if (filter.filterFlat.TypeCard != null)
                {
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataState == filter.filterFlat.TypeCard);
                }
                if (filter.filterFlat.PriceFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice >= filter.filterFlat.PriceFrom);
                if (filter.filterFlat.PriceTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice <= filter.filterFlat.PriceTo);
                if (filter.filterFlat.AreaFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FlatTotalArea >= filter.filterFlat.AreaFrom);
                if (filter.filterFlat.AreaTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(flat => flat.FlatTotalArea <= filter.filterFlat.AreaTo);
                if (filter.filterFlat.RegionId != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FlatRegionId == filter.filterFlat.RegionId);

                if (filter.filterFlat.TypeHouseId != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FlatHouseMaterial == filter.filterFlat.TypeHouseId);
                if (filter.filterFlat.Floors != null)
                {
                    switch (filter.filterFlat.Floors)
                    {
                        case "<5":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.FlatFloors < 5);
                                break;
                            }
                        case "5-8":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.FlatFloors >= 5);
                                filteredList = filteredList.ToList().FindAll(flat => flat.FlatFloors <= 8);
                                break;
                            }
                        case "9-16":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.FlatFloors >= 9);
                                filteredList = filteredList.ToList().FindAll(flat => flat.FlatFloors <= 16);
                                break;
                            }
                        case ">16":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.FlatFloors > 16);
                                break;
                            }
                    }
                }
                if (filter.filterFlat.RoomCount != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FlatRoomCount == (int)filter.filterFlat.RoomCount);
                AddFlatDataGridView(filteredList);
            }
            #endregion filterFlat
        }
        private void filterNewFlat()
        {
            var filter = new FilterWindow(TypeObject.Flat);
            filter.ShowDialog();
            #region filterFlat
            if (filter.filterFlat != null)
            {
                var flats = AppController.ImmoRepository.GetAllNewFlats();
                var filteredList = flats;

                if (filter.filterFlat.TypeCard != null)
                {
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataState == filter.filterFlat.TypeCard);
                }
                if (filter.filterFlat.PriceFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice >= filter.filterFlat.PriceFrom);
                if (filter.filterFlat.PriceTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice <= filter.filterFlat.PriceTo);
                if (filter.filterFlat.AreaFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.NewFlatTotalArea >= filter.filterFlat.AreaFrom);
                if (filter.filterFlat.AreaTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(flat => flat.NewFlatTotalArea <= filter.filterFlat.AreaTo);
                if (filter.filterFlat.RegionId != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.NewFlatObjectRegionId == filter.filterFlat.RegionId);

                if (filter.filterFlat.TypeHouseId != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.NewFlatHouseMaterialId == filter.filterFlat.TypeHouseId);
                if (filter.filterFlat.Floors != null)
                {
                    switch (filter.filterFlat.Floors)
                    {
                        case "<5":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.NewFlatFloorsCount < 5);
                                break;
                            }
                        case "5-8":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.NewFlatFloorsCount >= 5);
                                filteredList = filteredList.ToList().FindAll(flat => flat.NewFlatFloorsCount <= 8);
                                break;
                            }
                        case "9-16":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.NewFlatFloorsCount >= 9);
                                filteredList = filteredList.ToList().FindAll(flat => flat.NewFlatFloorsCount <= 16);
                                break;
                            }
                        case ">16":
                            {
                                filteredList = filteredList.ToList().FindAll(flat => flat.NewFlatFloorsCount > 16);
                                break;
                            }
                    }
                }
                if (filter.filterFlat.RoomCount != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.NewFlatRoomsCount == (int)filter.filterFlat.RoomCount);
                AddNewFlatDataGridView(filteredList);
            }
            #endregion filterFlat
        }
        private void filterCommercial()
        {
            var filter = new FilterWindow(TypeObject.Commercial);
            filter.ShowDialog();

            #region commercialFlat

            if (filter.filterCommercial != null)
            {
                var commercial = AppController.ImmoRepository.GetAllCommercial();
                var filteredList = commercial;
                if (filter.filterCommercial.TypeCard != null)
                {
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataState == filter.filterCommercial.TypeCard);
                }
                if (filter.filterCommercial.PriceFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice >= filter.filterCommercial.PriceFrom);
                if (filter.filterCommercial.PriceTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice <= filter.filterCommercial.PriceTo);
                if (filter.filterCommercial.AreaFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.CommercialRealEstateTotalArea >= filter.filterCommercial.AreaFrom);
                if (filter.filterCommercial.AreaTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(flat => flat.CommercialRealEstateTotalArea <= filter.filterCommercial.AreaTo);
                if (filter.filterCommercial.RegionId != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.CommercialRealEstateRegionId == filter.filterCommercial.RegionId);
                ////
                if (filter.filterCommercial.TypeCommercial != null)
                filteredList =
                    filteredList.ToList().FindAll(
                        flat => flat.CommercialRealEstateTypeId == filter.filterCommercial.TypeCommercial);

               AddCommercialGridView(filteredList);
            }

            #endregion filterCommercial
        }
        private void filterPlot()
        {
            var filter = new FilterWindow(TypeObject.Plot);
            filter.ShowDialog();
            #region plotFlat
            if (filter.filterPlot != null)
            {
                var plot = AppController.ImmoRepository.GetAllPlots();
                var filteredList = plot;

                if (filter.filterPlot.TypeCard != null)
                {
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataState == filter.filterPlot.TypeCard);
                }
                if (filter.filterPlot.PriceFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice >= filter.filterPlot.PriceFrom);
                if (filter.filterPlot.PriceTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.FinancialData.FinancialDataPrice <= filter.filterPlot.PriceTo);
                if (filter.filterPlot.AreaFrom != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.PlotsArea >= filter.filterPlot.AreaFrom);
                if (filter.filterPlot.AreaTo != null)
                    filteredList =
                        filteredList.ToList().FindAll(flat => flat.PlotsArea <= filter.filterPlot.AreaTo);
                if (filter.filterPlot.RegionId != null)
                    filteredList =
                        filteredList.ToList().FindAll(
                            flat => flat.PlotsRegionId == filter.filterPlot.RegionId);
                ///////
                if (filter.filterPlot.IsCommunicate != null)
                {
                    if ((bool)filter.filterPlot.IsCommunicate)
                    {
                        if (filter.filterPlot.IsElect != null)
                            filteredList =
                                filteredList.ToList().FindAll(
                                    flat => flat.PlotsCommunicationElectricPower == filter.filterPlot.IsElect);
                        if (filter.filterPlot.IsGas != null)
                            filteredList =
                                filteredList.ToList().FindAll(
                                    flat => flat.PlotsCommunicationGasSupply == filter.filterPlot.IsGas);
                        if (filter.filterPlot.IsWater != null)
                            filteredList =
                                filteredList.ToList().FindAll(
                                    flat => flat.PlotsCommunicationWater == filter.filterPlot.IsWater);
                    }
                }
                AddPlotGridView(filteredList);
            }
            #endregion plotFlat
        }

        #endregion Filter

    }
}
